<template>
  <el-dialog
    title="个人信息"
    :visible.sync="open"
    custom-class="dialog"
    @open="dialogOpen"
    v-loading="initLoading"
    element-loading-text="获取好友列表中..."
  >
    <span>头像昵称</span>
    <div class="avartar" v-if="!initLoading">
      <img :src="getAvartar(user.userProfileUrl)" alt="" />
      <input
        type="file"
        ref="fileInput"
        @change="handleFileChange"
        style="display: none"
      />
      <div @click="selectImage">
        <el-avatar :src="getAvartar(user.userProfileUrl)"></el-avatar>
      </div>

      <div class="info">
        <input
          maxlength="10"
          type="text"
          v-model="user.userNickname"
          class="username input-span"
        />
        <textarea
          type="text"
          maxlength="40"
          v-model="user.userIntroduce"
          class="introduce auto-resize-textarea"
        ></textarea>
      </div>
    </div>

    <span>个人资料</span>
    <div class="group" v-if="!initLoading">
      <div class="item">
        <i class="icon icon-yonghu4 purple-icon"></i>
        <span class="title">名字</span>
        <input
          maxlength="8"
          type="text"
          v-model="user.userRealname"
          placeholder="未填写"
          class="input-span right-info"
        />
        <i class="el-icon-arrow-right"></i>
      </div>
      <div class="item">
        <i class="icon icon-wode green-icon"></i>
        <span class="title">性别</span>
        <i class="el-icon-arrow-right"></i>
        <el-select
          v-model="user.userGender"
          class="right-info"
          size="mini"
          filterable
          remote
          reserve-keyword
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div>
      <div class="item">
        <i class="icon icon-dianhua red-icon"></i>
        <span class="title">电话</span>
        <i class="el-icon-arrow-right"></i>
        <input
          maxlength="14"
          type="text"
          v-model="user.userPhone"
          placeholder="未填写电话"
          class="input-span right-info"
        />
      </div>
      <div class="item">
        <i class="icon icon-youxiang5 purple-icon"></i>
        <span class="title">邮箱</span>
        <i class="el-icon-arrow-right"></i>
        <input
          maxlength="20"
          type="text"
          v-model="user.userEmail"
          placeholder="未填写邮箱"
          class="input-span right-info"
        />
      </div>
      <div class="item">
        <i class="icon icon-shijian7 green-icon"></i>
        <span class="title">生日</span>
        <i class="el-icon-arrow-right"></i>
        <el-date-picker
          v-model="user.userBirthday"
          align="right"
          type="date"
          placeholder="选择日期"
          class="right-info el-date-picker"
          size="mini"
          :clearable="false"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </div>
      <el-button type="primary" @click="clickConfirm" class="update"
        >更新个人资料</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import service from "@/utils/request";
import { getAvartar } from "@/utils/tools";
const isPhone = /^1[3|4|5|7|8][0-9]\d{8}$/;
const isEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
export default {
  name: "changeInfoDialog",
  data() {
    return {
      open: false,
      user: {},
      initLoading: false,
      tempUser: {},
      options: [
        {
          value: "男",
          label: "男",
        },
        {
          value: "女",
          label: "女",
        },
        {
          value: "未知",
          label: "未知",
        },
      ],
    };
  },
  //监听打开dialog的事件
  created() {
    this.$bus.$on("openDialog", this.openDialog);
  },
  beforeDestroy() {
    this.$bus.$off("openDialog", this.openDialog);
  },
  methods: {
    getAvartar,
    //其他界面点击打开dialog时的处理
    openDialog(e) {
      if (e == 1) {
        this.open = true;
      }
    },
    dialogOpen() {
      this.user = JSON.parse(localStorage.getItem("user"));

      if (this.user) {
        if (!this.user.userNickname) {
          this.user.userNickname = "用户" + this.user.userId;
        }
        if (!this.user.userIntroduce) {
          this.user.userIntroduce = "这个人太懒，什么也没留下";
        }
        if (!this.user.userGender) {
          this.user.userGender = "未知";
        }
        //备份
        this.tempUser = JSON.parse(JSON.stringify(this.user));
      }
    },

    //选择图片
    handleFileChange(event) {
      const file = event.target.files[0];
      if (file) {
        console.log(file);

        let formData = new FormData();
        formData.append("file", file);

        service
          .post(`/user/uploadProfile/${this.user.userId}`, formData, {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          })
          .then((res) => {
            console.log(res);
            if (res.code == 200) {
              this.$message.success("头像修改成功");
              this.user.userProfileUrl = res.data;
              this.tempUser.userProfileUrl = res.data;
              localStorage.setItem("user", JSON.stringify(this.tempUser));
              this.$bus.$emit("updateUserInfo", this.tempUser);
            } else {
              this.$message.warning(`头像修改失败！${res.code}:${res.message}`);
            }
          })
          .catch((error) => {
            this.$message.error("头像修改失败！");
          });
      }
    },

    //点击图片
    selectImage() {
      this.$refs.fileInput.click();
    },

    checkUserInfo() {
      //1.邮箱电话同时为空
      if (!this.user.userEmail && !this.user.userPhone) {
        this.$message.warning("邮箱和电话至少需要一个不为空！");
        this.user.userEmail = this.tempUser.userEmail;
        this.user.userPhone = this.tempUser.userPhone;
        return false;
      }
      //2.邮箱格式不正确
      if (this.user.userEmail && !isEmail.test(this.user.userEmail)) {
        this.$message.warning("邮箱格式错误！");
        return false;
      }
      //3.电话格式不正确
      if (this.user.userPhone && !isPhone.test(this.user.userPhone)) {
        this.$message.warning("电话格式错误！");
        return false;
      }
      return true;
    },
    //点击提交时，处理一下
    clickConfirm() {
      //检查一下是不是合理
      if (!this.checkUserInfo()) {
        return;
      }
      if (this.user.userNickname == "") {
        this.user.userNickname = "用户" + this.user.userId;
      }

      const data = {
        userId: this.user.userId,
        userNickname: this.user.userNickname,
        userIntroduce: this.user.userIntroduce,
        userRealname: this.user.userRealname,
        userGender: this.user.userGender,
        userPhone: this.user.userPhone,
        userEmail: this.user.userEmail,
        userBirthday: this.user.userBirthday,
      };
      console.log(data);

      service
        .post("/user/update", data)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success("资料更新成功!");
            this.tempUser = res.data;
            localStorage.setItem("user", JSON.stringify(this.tempUser));

            this.$bus.$emit("updateUserInfo", this.tempUser);
            console.log("修改资料响应");
            console.log(res);
          } else {
            this.$message.warning(`资料更新失败!${res.message}`);
          }
        })
        .catch((error) => {
          this.$message.error("资料修改失败！");
        });
    },
  },
};
</script>
<style scoped lang="less">
/deep/.dialog {
  width: 450px;
  height: 620px;
  padding: 0 0 0 20px;
  font-weight: 700;
  border-radius: 20px;
  overflow: hidden;

  .update {
    border-radius: 10px;
    margin-top: 20px;
    font-size: 18px;
    width: 100%;
  }
}

/deep/ .el-input__inner {
  border: none;
  box-shadow: none;
  font-size: 14px;
  text-align: right;
  color: #000000;
}

.auto-resize-textarea {
  background-color: rgba(0, 0, 0, 0);
  width: 100%;
  border: none;
  outline: none;
  resize: none;
  font-family: inherit;
  overflow: hidden;
}

.input-span {
  border: none;
  outline: none;
  font-size: inherit;
  font-family: inherit;
  background: none;
  padding: 0;
  margin: 0;
  width: auto;
}

.avartar {
  width: 100%;
  margin: 5px 0 20px -10px;
  display: flex;
  height: 140px;
  flex-direction: column;
  align-items: center;
  position: relative;
  z-index: 0;

  img {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    object-fit: cover;
    filter: blur(8px);
    /* 确保 img 在最下面 */
  }

  /* 确保 .el-upload 在 img 之上 */
  .el-avatar {
    position: relative;
    margin-top: 10px;
    height: 70px;
    width: 70px;
    align-items: center;
    z-index: 10;
    border: 2px solid #c8c1c1;
  }

  .info {
    width: 80%;
    display: flex;
    flex-direction: column;
    z-index: 2;
    position: relative;

    .username {
      font-size: 18px;
      font-weight: 700;
      margin-bottom: 3px;
      text-align: center;
      color: #ffffff;
      text-shadow: 1px 2px #272626;
      /* 白色文字 */
      mix-blend-mode: difference;
    }

    .introduce {
      font-size: 12px;
      text-align: center;
      color: #ffffff;
      text-shadow: 1px 2px #5f5858;
      /* 白色文字 */
      mix-blend-mode: difference;
    }
  }
}

.purple-icon {
  color: #503e9d;
  background-color: #e9e8ee;
}

.green-icon {
  color: #facd5d;
  background-color: #fefaee;
}

.red-icon {
  color: #fb7545;
  background-color: #fff0eb;
}

.group {
  width: 100%;
  margin: 10px 0 0 -10px;

  .item {
    font-weight: 400;
    color: #666666;
    display: flex;
    align-items: center;
    height: 32px;
    position: relative;
    font-size: 14px;
    padding: 0 5px;
    cursor: pointer;
    margin-bottom: 15px;
    border-radius: 10px;
    border: 1px solid #ffffff;
    overflow: hidden;

    .el-select {
      width: 20%;
      padding: 0;
      margin-right: -25px;
    }

    .el-date-picker {
      width: 34%;
      margin-right: -30px;
      padding: 0;
    }

    .right-info {
      padding: 0 10px 0 0;
      line-height: 32px;
      color: #000000;
      position: absolute;
      text-align: right;
      right: 15px;
    }

    i {
      height: 32px;
      width: 32px;
      text-align: center;
      line-height: 32px;
      margin-right: 10px;
      font-size: 20px;
    }

    i:first-of-type {
      border-radius: 5px;
    }

    i:last-of-type {
      position: absolute;
      margin-right: -10px;
      right: 0;
      z-index: 10;
    }

    /* 清除浮动 */
    .clearfix::after {
      content: "";
      display: table;
      clear: both;
    }
  }

  .item:hover {
    border: 1px solid #d1cfcf;
  }
}
</style>
